package com.example.logicalthinking.broadcastbestpracice;

import android.app.NotificationManager;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.Manifest;

import org.litepal.crud.DataSupport;
import org.litepal.tablemanager.Connector;
import java.util.List;

public class LitepalActivity extends AppCompatActivity implements View.OnClickListener{
    private MyService.DownloadBinder downloadBinder;
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            downloadBinder = (MyService.DownloadBinder) service;
//            downloadBinder.startDownload();
//            downloadBinder.getProgress();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {


        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_litepal);
        // 取消通知
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        manager.cancel(1);

        Button createdb = (Button) findViewById(R.id.litepal_create);
        Button addData = (Button) findViewById(R.id.litepal_add);
        Button updateData = (Button) findViewById(R.id.litepal_update);
        Button deleteData = (Button) findViewById(R.id.litepal_delete);
        createdb.setOnClickListener(this);
        addData.setOnClickListener(this);
        updateData.setOnClickListener(this);
        deleteData.setOnClickListener(this);

        Button queryData = (Button) findViewById(R.id.litepal_query);
        queryData.setOnClickListener(this);
        Button nextPage = (Button) findViewById(R.id.next_page);
        nextPage.setOnClickListener(this);

        Button startService = (Button) findViewById(R.id.start_service);
        Button stopService = (Button) findViewById(R.id.stop_service);
        startService.setOnClickListener(this);
        stopService.setOnClickListener(this);

        Button binderService = (Button) findViewById(R.id.binder_service);
        Button unbinderService = (Button) findViewById(R.id.unbinder_service);
        binderService.setOnClickListener(this);
        unbinderService.setOnClickListener(this);

        // 下载任务
        Button startDownload = (Button) findViewById(R.id.start_download);
        Button pauseDownload = (Button) findViewById(R.id.pause_download);
        Button cancelDownload = (Button) findViewById(R.id.cancel_download);
        startDownload.setOnClickListener(this);
        pauseDownload.setOnClickListener(this);
        cancelDownload.setOnClickListener(this);

        Intent intent = new Intent(this, MyService.class);
        startService(intent);
        bindService(intent, connection, BIND_AUTO_CREATE);  // 绑定服务
        if (ContextCompat.checkSelfPermission(LitepalActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
                PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(LitepalActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 3);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.litepal_create:{
                Connector.getDatabase();
                Toast.makeText(LitepalActivity.this, "create successed", Toast.LENGTH_LONG).show();
            }
                break;
            case R.id.litepal_add:{
                Story story = new Story();
                story.setName("Crazy English");
                story.setAuthor("Zhang Le");
                story.setPages(123);
                story.setPrice(88.88);
                story.setPress("Unknow");
                story.save();
                Story story2 = new Story();
                story2.setName("Crazy English");
                story2.setAuthor("Zhang Yi");
                story2.setPages(111);
                story2.setPrice(11.11);
                story2.setPress("Unknow");
                story2.save();
                Toast.makeText(LitepalActivity.this, "add successed", Toast.LENGTH_LONG).show();
            }
            break;
            case R.id.litepal_update:{
                Story story = new Story();
                story.setPrice(74.11);
                story.setPress("Anchor");
                // 更新成默认值
//                story.setToDefault("pages");
                story.updateAll("name = ? and author = ?", "Crazy English", "Zhang Yi");
                Toast.makeText(LitepalActivity.this, "update successed", Toast.LENGTH_LONG).show();
            }
            break;
            case R.id.litepal_delete:{
                DataSupport.deleteAll(Story.class, "price > ?", "80");
                Toast.makeText(LitepalActivity.this, "delete successed", Toast.LENGTH_LONG).show();
            }
            break;
            case R.id.litepal_query:{
                List<Story> storys = DataSupport.findAll(Story.class);
                for (Story story : storys){
                    Log.d("LitepalActivity", "story name is " + story.getName());
                    Log.d("LitepalActivity", "story author is " + story.getAuthor());
                    Log.d("LitepalActivity", "story pages is " + story.getPages());
                    Log.d("LitepalActivity", "story price is " + story.getPrice());
                    Log.d("LitepalActivity", "story press is " + story.getPress());
                }
                Toast.makeText(LitepalActivity.this, "query successed", Toast.LENGTH_LONG).show();
            }
            break;
            case R.id.next_page:{
                Intent intent = new Intent(LitepalActivity.this, CameraAlbumActivity.class);
                startActivity(intent);
            }
            break;
            case R.id.start_service:{
                Intent startIntent = new Intent(this, MyService.class);
                startService(startIntent);
            }
               break;
            case R.id.stop_service:{
                Intent stopService = new Intent(this, MyService.class);
                stopService(stopService);
            }
               break;
            case R.id.binder_service:{
                Intent binderIntent = new Intent(this, MyService.class);
                bindService(binderIntent, connection, BIND_AUTO_CREATE); // 绑定服务
            }
            break;
            case R.id.unbinder_service:{
                unbindService(connection); // 解绑服务
            }
            break;

            case R.id.start_download:{
                if (downloadBinder != null){
                    String url = "https://raw.githubusercontent.com/guolindev/eclipse/master/eclipse-inst-win64.exe";
                    downloadBinder.startDownload(url);
                }
            }
            break;
            case R.id.pause_download:{
                if (downloadBinder != null){
                    downloadBinder.pauseDownload();
                }

            }
            break;
            case R.id.cancel_download:{
                if (downloadBinder != null){
                    downloadBinder.cancelDownload();
                }
            }
            break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode){
            case 3:{
                if (grantResults.length > 0 && grantResults[0] != PackageManager.PERMISSION_GRANTED){
                    Toast.makeText(LitepalActivity.this, "拒绝权限将无法使用程序", Toast.LENGTH_LONG).show();
                    finish();
                }
            }
            break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(connection);
        // 如果活动被销毁了，一定要对服务进行解绑，不然可能造成内存泄漏
    }
}
